import { createRouter, createWebHistory } from 'vue-router'
import layout from '../views/layout/index.vue'
import Cookies from "js-cookie"

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: layout,
      redirect: "/dashboard",
      children: [
        {
          path: '/dashboard',
          component: () => import("../views/DashboardView.vue"),
          meta: { title: "首页" }
        },
      ]
    },
    {
      path: '/user',
      component: layout,
      redirect: "/student",
      meta: { title: "用户管理" },
      children: [
        {
          path: '/student',
          component: () => import("../views/user/student.vue"),
          meta: { title: "学生管理" },
        },
        {
          path: '/teacher',
          component: () => import("../views/user/teacher.vue"),
          meta: { title: "教师管理" },
        },
      ]
    },
    {
      path: '/exam',
      component: layout,
      redirect: "/paper",
      meta: { title: "卷题管理" },
      children: [
        {
          path: '/paper',
          component: () => import("../views/exam/paper.vue"),
          meta: { title: "试卷管理" },
        },
        {
          path: '/question',
          component: () => import("../views/exam/question.vue"),
          meta: { title: "题目管理" },
        },
      ]
    },
    {
      path: '/task',
      component: layout,
      redirect: "/list",
      meta: { title: "任务管理" },
      children: [
        {
          path: '/list',
          component: () => import("../views/task/list.vue"),
          meta: { title: "任务列表" },
        },
        {
          path: '/edit',
          component: () => import("../views/task/edit.vue"),
          meta: { title: "任务创建" },
        },
      ]
    },
    {
      path: '/education',
      component: layout,
      redirect: "/subject",
      meta: { title: "教育管理" },
      children: [
        {
          path: '/subject',
          component: () => import("../views/SubjectView.vue"),
          meta: { title: "学科列表" }
        },
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import("../views/LoginView.vue"),
      meta: {
        hidden: true
      }
    },
  ],
})

// 路由守卫
router.beforeEach((to, form, next) => {
  // 1，是否登录
  const token = Cookies.get("JSESSIONID")
  if (token) {
    if (to.path == "/login") {
      next("/")
    } else {
      next()
    }
  } else {
    if (to.path == "/login") {
      // 如果去的是Login 就放行
      next()
    } else {
      // 如果去的不是login，就去登录页面
      next("/login")
    }
  }
})


export default router
